package com.starchen.optimalselection.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starchen.optimalselection.admin.mapper.AdminRoleMapper;
import com.starchen.optimalselection.admin.mapper.AdminUserRoleMapper;
import com.starchen.optimalselection.admin.model.AdminRole;
import com.starchen.optimalselection.admin.model.AdminUserRole;
import com.starchen.optimalselection.admin.model.form.AssginRoleForm;
import com.starchen.optimalselection.admin.model.vo.UserRoleVo;
import com.starchen.optimalselection.admin.service.AdminUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author daxilong
 * @date 2025/3/21 17:41
 */
@Service
public class AdminUserRoleServiceImpl extends ServiceImpl<AdminUserRoleMapper, AdminUserRole> implements AdminUserRoleService {

    @Autowired
    private AdminRoleMapper roleMapper;

    /**
     * 获取用户的角色数据
     * @param userId
     * @return
     */
    @Override
    public UserRoleVo getUserRole(Long userId) {
        //获取所有角色
        List<AdminRole> roles = roleMapper.selectList(null);
        //根据用户id查询，已经分配角色
        QueryWrapper<AdminUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<AdminUserRole> userRolesList = baseMapper.selectList(wrapper);
        //从userRoles集合获取所有角色id
        List<Long> userRoleIds = userRolesList.stream().map(item -> item.getRoleId()).collect(Collectors.toList());

        UserRoleVo userRoleVo = new UserRoleVo();
        userRoleVo.setRoles(roles);
        userRoleVo.setUserRoleIds(userRoleIds);
        return userRoleVo;
    }

    /**
     * 为用户分配角色
     */
    @Override
    public void relationSet(AssginRoleForm assginRoleVo) {
        //根据用户id删除之前分配角色
        QueryWrapper<AdminUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",assginRoleVo.getUserId());
        baseMapper.delete(wrapper);
        //获取所有角色id，添加角色用户关系表
        //角色id列表
        List<Long> roleIdList = assginRoleVo.getRoleIdList();

        List<AdminUserRole> userRoleList = roleIdList.stream().map(item -> {
            AdminUserRole userRole = new AdminUserRole();
            userRole.setUserId(assginRoleVo.getUserId());
            userRole.setRoleId(item);
            return userRole;
        }).collect(Collectors.toList());

        saveBatch(userRoleList);
    }

}
